package edu.ynu.se.xiecheng.achitectureclass.demo.controller;

import edu.ynu.se.xiecheng.achitectureclass.common.controller.LogicController;
import edu.ynu.se.xiecheng.achitectureclass.demo.dao.SensorDataDao;
import edu.ynu.se.xiecheng.achitectureclass.demo.entity.data.SensorData;
import edu.ynu.se.xiecheng.achitectureclass.demo.service.SensorDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "传感器")
@RestController
@RequestMapping("/api/sensor-datas")
@CrossOrigin
public class SensorDataController extends LogicController<SensorDataService, SensorDataDao, SensorData, Long> {

    public SensorDataController(@Autowired SensorDataService ls) {
        super(ls);
    }

    @ApiOperation("通过设备ID获取最新设备数据")
    @GetMapping("/device/{deviceId}")
    public ResponseEntity<?> getLastSensorData(@PathVariable("deviceId") Long deviceId) {
        SensorData sensorData = getService().findLastSensorDataByDeviceId(deviceId);
        if (sensorData == null) {
            return ResponseEntity.noContent().build();
        }else {
            Map<String, Object> map = new HashMap<>();
            map.put("sensor_type", sensorData.getSensorType());
            map.put("value", sensorData.getValue());
            return ResponseEntity.ok(map);
        }
    }
    @ApiOperation("通过设备ID和条数获取最后多少条数据")
    @GetMapping("/device/lastnumbers")
    public ResponseEntity<?> getLastSensorDataByDeviceId(@RequestParam("deviceId") Long deviceId, @RequestParam("numbers") Integer numbers) {
        List<SensorData> sensorDataList = getService().findLastNumbersSensorDataByDeviceId(deviceId, numbers);
        if (sensorDataList == null) {
            return ResponseEntity.noContent().build();
        }else {
            Map<String, List<SensorData>> map = new HashMap<>();
            map.put("data", sensorDataList);
            return ResponseEntity.ok(map);
        }
    }

}